package com.promis.widget.mediapicker.ui;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.promis.luban.Luban;
import com.promis.luban.OnCompressListener;
import com.promis.util.CollectionUtils;
import com.promis.util.StringUtils;
import com.promis.widget.R;
import com.promis.widget.listener.OnAvoidMultiClickListener;
import com.promis.widget.mediapicker.data.ImageLoader;
import com.promis.widget.mediapicker.entity.ImageParcelable;
import com.promis.widget.mediapicker.manager.ImagePickerManager;
import com.promis.widget.mediapicker.manager.MediaPickerConstants;
import com.promis.widget.mediapicker.ImagePreviewApi;
import com.promis.widget.mediapicker.manager.ImagePreviewListener;
import com.promis.widget.mediapicker.data.DataCallback;
import com.promis.widget.mediapicker.entity.FolderParcelable;
import com.promis.widget.mediapicker.entity.MediaParcelable;
import com.promis.widget.mediapicker.util.ScreenUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jidanbo on 2018/3/26.
 */

public class ImagePickerActivity extends AppCompatActivity implements DataCallback {

    private ImageView imgvClose;
    private TextView txtvTitle;

    private Button btnvSubmit;
    private Button btnvFolder;
    private Button btnvPreview;

    private RecyclerView rylvMedia;
    private ImageGridAdapter adptMedia;

    private ListPopupWindow mFolderPopupWindow;
    private FolderAdapter mFolderAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mediapicker_picker);

        imgvClose = findViewById(R.id.activity_media_picker_imgv_close);
        txtvTitle = findViewById(R.id.activity_media_picker_txtv_title);

        btnvSubmit = findViewById(R.id.activity_media_picker_btnv_submit);
        btnvFolder = findViewById(R.id.activity_media_picker_btnv_folder);
        btnvPreview = findViewById(R.id.activity_media_picker_btnv_preview);

        rylvMedia = findViewById(R.id.activity_media_picker_rylv_grid);

        initData();
        initListener();
    }

    private void initData() {
        getLoaderManager().initLoader(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE,null,new ImageLoader(this,this));

        GridLayoutManager mLayoutManager = new GridLayoutManager(this, MediaPickerConstants.GridSpanCount);
        rylvMedia.setLayoutManager(mLayoutManager);
        rylvMedia.addItemDecoration(new SpacingDecoration(MediaPickerConstants.GridSpanCount, MediaPickerConstants.GridSpace));
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        rylvMedia.setHasFixedSize(true);
        adptMedia = new ImageGridAdapter(this, ImagePickerManager.getInstance().getMaxFileCount(), ImagePickerManager.getInstance().getMaxFileSize());
        rylvMedia.setAdapter(adptMedia);

        ArrayList<FolderParcelable> folders=new ArrayList<>();
        mFolderAdapter=new FolderAdapter(folders,this);
        mFolderPopupWindow = new ListPopupWindow(this);
        mFolderPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        mFolderPopupWindow.setAdapter(mFolderAdapter);
        mFolderPopupWindow.setHeight((int)(ScreenUtils.getScreenHeight(this)*0.6));
        mFolderPopupWindow.setWidth(ScreenUtils.getScreenWidth(this));
        mFolderPopupWindow.setAnchorView(btnvFolder);
        mFolderPopupWindow.setModal(true);
        mFolderPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mFolderAdapter.setSelectIndex(position);
                btnvFolder.setText(mFolderAdapter.getItem(position).name);

                List<ImageParcelable> imageList = new ArrayList<>();
                for (MediaParcelable media : mFolderAdapter.getSelectMedias()) {
                    if (media instanceof ImageParcelable) {
                        imageList.add((ImageParcelable) media);
                    }
                }

                filter(imageList);
                adptMedia.notifyDataSetChanged(imageList);
                mFolderPopupWindow.dismiss();
            }
        });

        if (ImagePickerManager.getInstance().getMaxFileCount() == 1) {
            btnvSubmit.setVisibility(View.GONE);
        }
    }

    private void initListener() {
        imgvClose.setOnClickListener(new OnAvoidMultiClickListener() {
            @Override
            public void onAvoidMultiClick(View v) {
                finish();
            }
        });

        adptMedia.setOnItemClickListener(new ImageGridAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, ImageParcelable image, List<ImageParcelable> selectMedias) {
                setButtonText();
                if (ImagePickerManager.getInstance().getMaxFileCount() == 1) {
                    done(adptMedia.getSelectedImageList());
                }
            }
        });

        btnvFolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mFolderPopupWindow.isShowing()){
                    mFolderPopupWindow.dismiss();
                }else{
                    mFolderPopupWindow.show();
                }
            }
        });

        btnvPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CollectionUtils.isNullOrEmpty(adptMedia.getSelectedImageList())) {
                    Toast.makeText(getBaseContext(), "请选择图片后预览", Toast.LENGTH_LONG).show();
                    return;
                }

                ImagePreviewApi.with(getBaseContext()).list(adptMedia.getSelectedImageList()).position(0).subscribe(new ImagePreviewListener() {
                    @Override
                    public void onDeleteCompleted(ImageParcelable image) {
                        adptMedia.setSelectMedias(image);
                    }
                }).open();
            }
        });

        btnvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                done(adptMedia.getSelectedImageList());
            }
        });
    }

    @Override
    public void onData(ArrayList<FolderParcelable> list) {

        ArrayList<MediaParcelable> mediaList = list.get(0).getMedias();

        btnvFolder.setText(list.get(0).name);
        setButtonText();
        mFolderAdapter.updateAdapter(list);

        List<ImageParcelable> imageList = new ArrayList<>();
        for (MediaParcelable media : mediaList) {
            if (media instanceof ImageParcelable) {
                imageList.add((ImageParcelable) media);
            }
        }
        filter(imageList);
        adptMedia.notifyDataSetChanged(imageList);
    }

    private void filter(List<ImageParcelable> imageList) {
        if (CollectionUtils.isNullOrEmpty(ImagePickerManager.getInstance().getFilterImageList())) return;
        for (MediaParcelable select : ImagePickerManager.getInstance().getFilterImageList()) {
//            for (ImageParcelable image : imageList) {
//                if (select.localPath.equals(image.localPath)) {
//                    imageList.remove(image);
//                    break;
//                }
//            }
            imageList.remove(select);
        }
    }

    private void setButtonText(){
        btnvSubmit.setText(getString(R.string.done)+"("+adptMedia.getSelectedImageList().size()+"/"+ ImagePickerManager.getInstance().getMaxFileCount()+")");
        btnvPreview.setText(getString(R.string.preview)+"("+adptMedia.getSelectedImageList().size()+")");
    }

    public void done(final List<ImageParcelable> selectedImageList){
        if (ImagePickerManager.getInstance().getImagePickerListener() != null) {

            List<String> filePathList = new ArrayList<>(selectedImageList.size());
            for (int i = 0; i < selectedImageList.size(); i++) {
                if (selectedImageList.get(i) == null || StringUtils.isNullOrEmpty(selectedImageList.get(i).localPath)) return;
                File sourceFile = new File(selectedImageList.get(i).localPath);
                if (!sourceFile.exists()) return;

                filePathList.add(selectedImageList.get(i).localPath);
            }

            final List<File> fileList = new ArrayList<>();
            Luban.with(getBaseContext()).load(filePathList).ignoreBy(50)
                    .setCompressListener(new OnCompressListener() { //设置回调
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        }

                        @Override
                        public void onSuccess(File file, int position) {
                            // TODO 压缩成功后调用，返回压缩后的图片文件

                            ImageParcelable image = selectedImageList.get(position);
                            image.compressPath = file.getPath();

                            fileList.add(file);
                            if (fileList.size() == selectedImageList.size()) {
                                if (ImagePickerManager.getInstance().getImagePickerListener() != null) {
                                    ImagePickerManager.getInstance().getImagePickerListener().onPickCompleted(selectedImageList);
                                }
                                finish();
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过程出现问题时调用
                        }
                    }).launch();
        }
    }

    @Override
    protected void onDestroy() {
        Glide.get(this).clearMemory();
        super.onDestroy();
    }
}
